<template>
  <div class="app-container">
    <div class="card-box">
      <el-button type="primary" @click="handleCreate">添加应用</el-button>
    </div>
    <div class="card-box">
      <el-table
        v-loading="thirdAppStore.loading.list"
        :data="thirdAppStore.list"
        style="width: 100%"
      >
        <el-table-column prop="name" label="应用名称" />
        <el-table-column prop="appid" label="APPID" />
        <el-table-column label="所属用户" prop="user.username" />
        <el-table-column label="创建时间" prop="created_at" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-popconfirm title="确定删除?" placement="top" @confirm="handleDelete(row)">
              <template #reference>
                <el-button link type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-model:page="listQuery.page"
        v-model:limit="listQuery.size"
        :total="thirdAppStore.totalCount"
        @pagination="thirdAppStore.fetchList(listQuery)"
      />
    </div>
    <Form v-model="visible" :type="formType" :form="currentRow" @confirm="handleConfirm" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ThirdAppFormType, ThirdAppType } from "@/api/system/third-app";
import { useThirdAppStoreHook } from "@/store/modules/system/third-app";
import Form, { type FormType } from "./components/form.vue";
import Pagination from "@/components/Pagination/index.vue";

const router = useRouter();
const thirdAppStore = useThirdAppStoreHook();

const listQuery = reactive({
  page: 1,
  size: 20,
});

const visible = ref(false);

const formType = ref<FormType>("add");

const currentRow = ref<ThirdAppFormType>({
  name: "",
  appid: "",
  user: "",
  secret_key: "",
  aes_key: "",
  server_addr: "",
  enable_whitelist: false,
  whitelist: "",
});

onMounted(async () => {
  await thirdAppStore.fetchList(listQuery);
});

function handleCreate() {
  formType.value = "add";
  visible.value = true;
}

function handleEdit(row: ThirdAppType) {
  formType.value = "edit";
  currentRow.value = {
    id: row.id,
    name: row.name,
    appid: row.appid,
    user: row.user.id,
    secret_key: row.secret_key,
    aes_key: row.aes_key,
    server_addr: row.server_addr,
    enable_whitelist: row.enable_whitelist,
    whitelist: row.whitelist,
  };
  visible.value = true;
}

async function handleDelete(row: ThirdAppType) {
  await thirdAppStore.fetchDelete(row.id);
  thirdAppStore.fetchList(listQuery);
}

function handleConfirm() {
  thirdAppStore.fetchList(listQuery);
}
</script>
